package cn.pud.rpademo01.utils;

import cn.pud.rpademo01.EmailConstants;
import com.sun.mail.imap.IMAPStore;
import lombok.Data;

import javax.mail.*;
import javax.mail.search.FlagTerm;
import java.util.HashMap;
import java.util.Properties;

/**
 * @Author: Miyako
 * @Date: 2024-11-12-9:25
 * @Description: 邮箱工具类
 */
@Data
public class EmailUtil {

    EmailModel emailModel;

    public EmailUtil(EmailModel emailModel) {
        this.emailModel = emailModel;
    }

    private IMAPStore connectionToImap() {
        try {
            Properties properties = new Properties();
            properties.put(EmailConstants.EMAIL_PROPERTIES_PROTOCOL, "imap");
            properties.put(EmailConstants.EMAIL_PROPERTIES_IMAP_TIMEOUT, "5000");
            Session emailSession = Session.getDefaultInstance(properties);
            HashMap IAM = new HashMap<>();
            IAM.put("name", "Miyako");
            // 使用imap会话机制，连接服务器
            IMAPStore store = (IMAPStore) emailSession.getStore("imap");
            System.out.println(emailModel.getImapHost() + emailModel.getUsername() + emailModel.getPassword());
            store.connect(emailModel.getImapHost(), emailModel.getUsername(), emailModel.getPassword());
            //网易邮箱需要配置imap进行
            store.id(IAM);
            return store;
        } catch (Exception e) {
            throw new RuntimeException("邮箱IMAP服务连接异常");
        }
    }


    /*
     * @description:查询所有邮件
     * @return: 返回邮件数组
     **/
    public Message[] acceptAllEmail() {
        IMAPStore store = connectionToImap();
        try {
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);
            // 获取邮件内容数组
            Message[] messages = folder.getMessages();
            System.out.println("Total messages: " + messages.length);
            return messages;
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * @description:只获取未读邮件,并标记为已读
     **/
    public Message[] acceptNewEmail() {
        IMAPStore store = connectionToImap();
        try {
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);
            // 创建搜索条件，仅搜索未读邮件
            Message[] messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
            System.out.println("Total unread messages: " + messages.length);
            // 将获取到的未读邮件标记为已读,避免下次重复读取
            for (Message message : messages) {
                message.setFlag(Flags.Flag.SEEN, true);  // 标记邮件为已读，服务器上会同步更新
            }
            return messages;
        } catch (MessagingException e) {
            throw new RuntimeException("获取未读邮件异常", e);
        }

    }


}
